import React, { useEffect, useState } from 'react';
import { ProFormSelect } from '@ant-design/pro-components';
import { Card, Form, Input, Row, Col, DatePicker, TimePicker, message } from 'antd';
import dayjs from 'dayjs';
import { TruckPreOrder } from '../../types';
import AddressInput from './AddressInput';
import PackageInfo from './PackageInfo';
import { get_map } from '@/services/system_api';
import { FormattedMessage, useIntl } from "@umijs/max";
import PhoneInput from 'react-phone-number-input';
import 'react-phone-number-input/style.css';

interface AddressDetailsProps {
  form: any;
  formData: TruckPreOrder;
  setFormData: (data: any) => void;
}

const AddressDetails: React.FC<AddressDetailsProps> = ({ form, formData, setFormData }) => {
  const intl = useIntl();
  const [initAdditionalItems, setInitAdditionalItems] = useState<any>([]);
  const [initDivAdditionalItems, setInitDivAdditionalItems] = useState<any>([]);
  const [pickReadyDate, setPickReadyDate] = useState(formData.pickReadyDatetime ? dayjs(formData.pickReadyDatetime) : dayjs());
  useEffect(() => {
    const fetchFeeOptions = async () => {
      await initAdditionalItemsFunc();  
      await initDivAdditionalItemsFunc(); 
      initClearData();
    };
    fetchFeeOptions();
  }, []); 

  useEffect(() => {
    console.log("pickReadyDate changed: ", pickReadyDate);
  }, [pickReadyDate]);

  const initAdditionalItemsFunc = async () => {
    try {
      const response = await get_map("elm_additional_service");
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      const data = [
        { value: 'None', label: intl.formatMessage({ id: 'option.none' }) },
        ...response.data
      ];
      setInitAdditionalItems(data);
    } catch (error) {
      message.error(error.message);
    }
  };

  const initClearData = () => {
    setFormData(prev => ({
      ...prev,
      deliveryAddress: {
        ...(prev.deliveryAddress || {}),
        ['accessorials']: '',
        ['accessorialsArray']: []
      },
      shipperAddress: {
        ...(prev.shipperAddress || {}),
        ['accessorials']: '',
        ['accessorialsArray']: []
      }
    }));
  };
  
  const initDivAdditionalItemsFunc = async () => {
    try {
      const response = await get_map("elm_delivery_additional_service");
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      const data = [
        { value: 'None', label: intl.formatMessage({ id: 'option.none' }) },
        ...response.data
      ];
      setInitDivAdditionalItems(data);
    } catch (error) {
      message.error(error.message);
    }
  };

  // 各种处理函数保持不变，只是显示文本使用国际化
  const handleDivAdditionalServiceChange = (field: string, value: any) => {
    const addItems = value.join(',');
    setFormData(prev => ({
      ...prev,
      deliveryAddress: {
        ...(prev.deliveryAddress || {}),
        [field]: addItems,
        ['accessorialsArray']: value
      }
    }));
  };

  const handleAdditionalServiceChange = (field: string, value: any) => {
    const addItems = value.join(',');
    setFormData(prev => ({
      ...prev,
      shipperAddress: {
        ...(prev.shipperAddress || {}),
        [field]: addItems,
        ['accessorialsArray']: value
      }
    }));
  };

  const handleShipperAddressChange = (field: string, value: any) => {
    console.log("change shipper address:", field, value);
    setFormData(prev => ({
      ...prev,
      shipperAddress: {
        ...(prev.shipperAddress || {}),
        [field]: value
      }
    }));
  };

  const handleDeliveryAddressChange = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      deliveryAddress: {
        ...(prev.deliveryAddress || {}),
        [field]: value
      }
    }));
  };

  const handleAddressChange = (type: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [`${type}`]: value
    }));
  };

  const shipperAddress = formData.shipperAddress || {};
  const deliveryAddress = formData.deliveryAddress || {};

  // const postalCodeRules = [
  //   { 
  //     required: true, 
  //     message: intl.formatMessage({ id: 'validation.postalCode.required' }) 
  //   },
  //   {
  //     pattern: /^\d{5}(-\d{4})?$/,
  //     message: intl.formatMessage({ id: 'validation.postalCode.format' })
  //   }
  // ];

  const emailRules = [
    { 
      required: true, 
      message: intl.formatMessage({ id: 'validation.email.required' }) 
    },
    { 
      pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
      message: intl.formatMessage({ id: 'validation.email.format' })
    }
  ];

  const phoneRules = [
    { 
      required: true, 
      message: intl.formatMessage({ id: 'validation.phone.required' }) 
    },
    {
      validator: (_, value) => {
        if (!value) return Promise.resolve();
        const isValid = value.replace(/\D/g, "").length >= 10;
        return isValid
          ? Promise.resolve()
          : Promise.reject(new Error(intl.formatMessage({ id: 'validation.phone.format' })));
      },
    }
  ];

  const range = (start: number, end: number) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col xs={24} xxl={12}>
          <Card
            title={intl.formatMessage({
              id: "pages.order.shipperAddress.title",
            })}
            style={{ minWidth: "500px" }}
          >
            <Form layout="vertical">
              <Form.Item
                label={intl.formatMessage({ id: "pages.order.address.pickup" })}
              >
                <AddressInput
                  value={formData.shipperAddressDT}
                  onChange={(v) => handleAddressChange("shipperAddressDT", v)}
                />
              </Form.Item>

              <Form.Item
                label={intl.formatMessage({
                  id: "pages.order.address.company",
                })}
                name={"oaCompany"}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: "validation.company.required",
                    }),
                  },
                ]}
                extra={intl.formatMessage({
                  id: "pages.order.address.company.extra",
                })}
              >
                <Input
                  value={shipperAddress.oaCompany}
                  onChange={(e) =>
                    handleShipperAddressChange("oaCompany", e.target.value)
                  }
                />
              </Form.Item>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.email",
                    })}
                    name={"oaEmail"}
                    initialValue={shipperAddress.oaEmail}
                    rules={emailRules}
                  >
                    <Input
                      value={shipperAddress.oaEmail}
                      onChange={(e) =>
                        handleShipperAddressChange("oaEmail", e.target.value)
                      }
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.contact",
                    })}
                    name={"oaFirstname"}
                  >
                    <Input.Group compact>
                      <Input
                        style={{ width: "50%" }}
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.contact.lastName",
                        })}
                        value={shipperAddress.oaFirstname}
                        onChange={(e) =>
                          handleShipperAddressChange(
                            "oaFirstname",
                            e.target.value
                          )
                        }
                      />
                      <Input
                        style={{ width: "50%" }}
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.contact.firstName",
                        })}
                        value={shipperAddress.oaLastname}
                        onChange={(e) =>
                          handleShipperAddressChange(
                            "oaLastname",
                            e.target.value
                          )
                        }
                      />
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={18}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.phone",
                    })}
                    name={"oaTelphone"}
                    initialValue={shipperAddress.oaTelphone}
                    rules={phoneRules}
                  >
                    <PhoneInput
                      international
                      defaultCountry="US"
                      value={shipperAddress.oaTelphone}
                      onChange={(value) =>
                        handleShipperAddressChange("oaTelphone", value)
                      }
                      placeholder={intl.formatMessage({
                        id: "pages.order.address.phone.placeholder",
                      })}
                    />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.extension",
                    })}
                    initialValue={shipperAddress.oaTelphoneExtension}
                  >
                    <Input
                      value={shipperAddress.oaTelphoneExtension}
                      onChange={(e) =>
                        handleShipperAddressChange(
                          "oaTelphoneExtension",
                          e.target.value
                        )
                      }
                    />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.reference",
                    })}
                  >
                    <Input
                      value={shipperAddress.referenceNo}
                      onChange={(e) =>
                        handleShipperAddressChange(
                          "referenceNo",
                          e.target.value
                        )
                      }
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <ProFormSelect
                    name="accessorials"
                    label={intl.formatMessage({
                      id: "pages.order.address.special",
                    })}
                    allowClear
                    mode="multiple"
                    placeholder={intl.formatMessage({
                      id: "pages.order.address.special.placeholder",
                    })}
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({
                          id: "validation.accessorials.required",
                        }),
                      },
                    ]}
                    fieldProps={{
                      style: { width: 180 },
                      onChange: (value) =>
                        handleAdditionalServiceChange("accessorials", value),
                    }}
                    options={initAdditionalItems}
                  />
                </Col>
              </Row>

              <Form.Item
                label={intl.formatMessage({ id: "pages.order.address.notes" })}
              >
                <Input.TextArea
                  rows={3}
                  value={shipperAddress.note}
                  onChange={(e) =>
                    handleShipperAddressChange("note", e.target.value)
                  }
                />
              </Form.Item>

              <Row gutter={16}>
                <Col span={16}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.businessHours",
                    })}
                    name={"openTime"}
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({
                          id: "validation.businessHours.required",
                        }),
                      },
                    ]}
                  >
                    <Input.Group compact>
                      <TimePicker
                        format="HH:mm"
                        onChange={(time) =>
                          handleShipperAddressChange(
                            "openTime",
                            dayjs(time).format("HHmm")
                          )
                        }
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.businessHours.start",
                        })}
                      />{" "}
                      --
                      <TimePicker
                        format="HH:mm"
                        onChange={(time) =>
                          handleShipperAddressChange(
                            "closeTime",
                            dayjs(time).format("HHmm")
                          )
                        }
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.businessHours.end",
                        })}
                      />
                    </Input.Group>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="pickReadyDatetime"
                    label={intl.formatMessage({
                      id: "pages.order.address.pickupTime",
                    })}
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({
                          id: "validation.pickupTime.required",
                        }),
                      },
                    ]}
                  >
                    <DatePicker
                      showTime={{ format: "HH:mm", showSecond: false }}
                      format="YYYY-MM-DD HH:mm"
                      style={{ width: "60%" }}
                      value={pickReadyDate}
                      onChange={(_, timeStrings) =>
                        handleShipperAddressChange(
                          "pickReadyDatetime",
                          timeStrings
                        )
                      }
                      disabledDate={(current) =>
                        current && current < dayjs().startOf("day")
                      }
                      disabledTime={(current) => {
                        if (current && current.isSame(dayjs(), "day")) {
                          return {
                            disabledHours: () => range(0, dayjs().hour()),
                            disabledMinutes: (selectedHour) => {
                              if (selectedHour === dayjs().hour()) {
                                return range(0, dayjs().minute());
                              }
                              return [];
                            },
                          };
                        }
                        return {};
                      }}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Card>
        </Col>
        <Col xs={24} xxl={12}>
          <Card
            title={intl.formatMessage({
              id: "pages.order.receiverAddress.title",
            })}
            style={{ minWidth: "500px" }}
          >
            <Form layout="vertical">
              <Form.Item
                label={intl.formatMessage({ id: "pages.order.address.pickup" })}
              >
                <AddressInput
                  value={formData.deliveryAddressDT}
                  onChange={(v) => handleAddressChange("deliveryAddressDT", v)}
                />
              </Form.Item>

              <Form.Item
                label={intl.formatMessage({
                  id: "pages.order.address.company",
                })}
                name={"oaCompany"}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: "validation.company.required",
                    }),
                  },
                ]}
                extra={intl.formatMessage({
                  id: "pages.order.address.company.extra",
                })}
              >
                <Input
                  value={deliveryAddress.oaCompany}
                  onChange={(e) =>
                    handleDeliveryAddressChange("oaCompany", e.target.value)
                  }
                />
              </Form.Item>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.email",
                    })}
                    name={"oaEmail"}
                    rules={emailRules}
                  >
                    <Input
                      value={deliveryAddress.oaEmail}
                      onChange={(e) =>
                        handleDeliveryAddressChange("oaEmail", e.target.value)
                      }
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.contact",
                    })}
                    name={"oaContact"}
                  >
                    <Input.Group compact>
                      <Input
                        style={{ width: "50%" }}
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.contact.lastName",
                        })}
                        value={deliveryAddress.oaFirstname}
                        onChange={(e) =>
                          handleDeliveryAddressChange(
                            "oaFirstname",
                            e.target.value
                          )
                        }
                      />
                      <Input
                        style={{ width: "50%" }}
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.contact.firstName",
                        })}
                        value={deliveryAddress.oaLastname}
                        onChange={(e) =>
                          handleDeliveryAddressChange(
                            "oaLastname",
                            e.target.value
                          )
                        }
                      />
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={18}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.phone",
                    })}
                    name={"oaTelphone"}
                    rules={phoneRules}
                  >
                    <PhoneInput
                      international
                      defaultCountry="US"
                      value={deliveryAddress.oaTelphone}
                      onChange={(value) =>
                        handleDeliveryAddressChange("oaTelphone", value)
                      }
                      placeholder={intl.formatMessage({
                        id: "pages.order.address.phone.placeholder",
                      })}
                    />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.extension",
                    })}
                  >
                    <Input
                      value={deliveryAddress.oaTelphoneExtension}
                      onChange={(e) =>
                        handleDeliveryAddressChange(
                          "oaTelphoneExtension",
                          e.target.value
                        )
                      }
                    />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.reference",
                    })}
                  >
                    <Input
                      value={deliveryAddress.referenceNo}
                      onChange={(e) =>
                        handleDeliveryAddressChange(
                          "referenceNo",
                          e.target.value
                        )
                      }
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <ProFormSelect
                    name="accessorials"
                    label={intl.formatMessage({
                      id: "pages.order.address.special",
                    })}
                    allowClear
                    mode="multiple"
                    placeholder={intl.formatMessage({
                      id: "pages.order.address.special.placeholder",
                    })}
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({
                          id: "validation.accessorials.required",
                        }),
                      },
                    ]}
                    fieldProps={{
                      style: { width: 180 },
                      onChange: (value) =>
                        handleDivAdditionalServiceChange("accessorials", value),
                    }}
                    options={initDivAdditionalItems}
                  />
                </Col>
              </Row>

              <Form.Item
                label={intl.formatMessage({ id: "pages.order.address.notes" })}
              >
                <Input.TextArea
                  rows={3}
                  value={deliveryAddress.note}
                  onChange={(e) =>
                    handleDeliveryAddressChange("note", e.target.value)
                  }
                />
              </Form.Item>

              <Row gutter={16}>
                <Col span={18}>
                  <Form.Item
                    label={intl.formatMessage({
                      id: "pages.order.address.businessHours",
                    })}
                    name={"openTime"}
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({
                          id: "validation.businessHours.required",
                        }),
                      },
                    ]}
                  >
                    <Input.Group compact>
                      <TimePicker
                        format="HH:mm"
                        onChange={(time) =>
                          handleDeliveryAddressChange(
                            "openTime",
                            dayjs(time).format("HHmm")
                          )
                        }
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.businessHours.start",
                        })}
                      />{" "}
                      --
                      <TimePicker
                        format="HH:mm"
                        onChange={(time) =>
                          handleDeliveryAddressChange(
                            "closeTime",
                            dayjs(time).format("HHmm")
                          )
                        }
                        placeholder={intl.formatMessage({
                          id: "pages.order.address.businessHours.end",
                        })}
                      />
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Card>
        </Col>
      </Row>
      <Row gutter={[16, 16]} style={{ marginTop: "10px" }}>
        <Col>
          <PackageInfo
            form={form}
            formData={formData}
            setFormData={setFormData}
          />
        </Col>
      </Row>
    </div>
  );
};

export default AddressDetails;